import { getLayoutProps } from "@/common/layout/getProps";
import { PageContainer } from "@ant-design/pro-layout";
import type { TableColumnsType } from "antd";
import { Button, Space } from "antd";
import { Row } from "antd";
import { Select } from "antd";
import { Descriptions, Divider, Form, Table,message,Input, type TableProps } from "antd";
import { assign } from "lodash";
import Router from "next/router";
import { useRouter } from "next/router";
import type { FC, Key} from "react";
import { useState,useEffect } from "react";
import { http } from "@/utils/request";

type TableDataType = {
  id: string;
  field1: string;
  field2: string;
  field3: string;
  field4: string;
  field5: string;
  field6: string;
  field7: string;
  field8: string;
  field9: string;
  field10: string;
  field11: string;
  field12: string;
}

type TableRowSelection<T> = TableProps<T>["rowSelection"];

const ComplaintCU = () => {
  const router = useRouter();
  const { query: { id, type } } = router;
  const [list, setList] = useState([]);
  const [detailData,setDetailData] = useState({});

  if (!id) {
    return null;
  }
  const columns = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text: string, _record: TableDataType, index: number) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "指标类型名称",
      dataIndex: "targetTypeName"
    },
    {
      align: "center",
      title: "指标名称",
      dataIndex: "targetName"
    },
    {
      align: "center",
      title: "指标定义",
      dataIndex: "targetContent"
    },
    {
      align: "center",
      title: "考核标准",
      dataIndex: "standard"
    },
    {
      align: "center",
      title: "权重",
      dataIndex: "targetWeight"
    },
    {
      align: "center",
      title: "自评得分",
      dataIndex: "selfScore"
    },
    {
      align: "center",
      title: "自评得分说明",
      dataIndex: "selfDesc"
    },
    {
      align: "center",
      title: "考评小组得分",
      dataIndex: "groupScore"
    },
    {
      align: "center",
      title: "考评小组得分说明",
      dataIndex: "groupScoreDesc"
    },
    {
      align: "center",
      title: "申诉标志",
      dataIndex: "appealFlag",
      fixed:'right',
      width: 120,
      render: (_,record) => {
        return (
          <>
          {type === "detail"&& record.appealFlag === "1" && <span>申诉</span>}
          {type === "detail"&& record.appealFlag === "2" && <span>不申诉</span>}
          {type !== "detail"&&
            <Select className={'w-full'} placeholder="请选择" value={record.appealFlag} onChange={(value)=>{
              const newData = list.map((item) => {
                if(item.id == record.id){
                  item.appealFlag = value
                  return item;
                }
                return item;
              });
              setList(newData);
            }} options={[
              { value: '0', label: '不申诉' },
              { value: '1', label: '申诉' }
            ]} />
          }
          </>
        )
      }
    },
    {
      align: "center",
      title: "申诉原因",
      fixed:'right',
      width: 180,
      dataIndex: "appealReason",
      render: (_,record) => {
        return (
          <>
          {type === "detail"&&
            <span>{record.appealReason}</span>
          }
          {type !== "detail"&&
            <Input className={'w-full'} placeholder="请输入" value={record.appealReason} onChange={(e) => {
              const newData = list.map((item) => {
                if(item.id == record.id){
                  item.appealReason = e.target.value
                  return item;
                }
                return item;
              });
              setList(newData);
              // employeeList[employeeIndex].editTableData.map((item) => {
              //   if(item.id == record.id){
              //     item.selfDesc = e.target.value
              //     return item;
              //   }
              //   return item;
              // });
              // setEmployeeList(employeeList);
            }}/>
          }
          </>
        )
      }
    },
  ] as TableColumnsType

  // const onSelectChange = (keys: Key[]) => {
  //   console.log(keys);
  //   setSelectedRowKeys(keys)
  // }

  // const rowSelection: TableRowSelection<TableDataType> = {
  //   selectedRowKeys,
  //   onChange: onSelectChange
  // }

  const submit = () => {
    const reqArr = list.map(item=>(
      {
      resultDetailId:item.id?item.id:null,
      appealFlag:item.appealFlag,
      appealReason:item.appealReason
    }));
    const addFormData = {
      pmEvaluResultAppealQuery:{
        resultId:id
      },
      pmEvaluResultAppealDetailQueryList:reqArr
    }
    addSave(addFormData)
  }
  //新增接口
  const addSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmEvaluResultAppeal/add',
        data:formData,
      })
      if(res.code == 200){
        message.success('绩效结果申诉成功!');
        Router.push('/performanceResultConfirmAndApply/performanceResultConfirm');
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //获取绩效结果详情
  const getDetailData = async()=>{
    try {
      const res = await http.get({
        url:'/PmEvaluResultDetail/qryById',
        params:{resultId:id}
      })
      if(res.code == 200){
        setList(res.data.pmEvaluResultDetailVoList)
        setDetailData({
          code:res.data.code,
          deptName:res.data.deptName,
          name:'张三',
          time:'2024-08-30',
          centerGroupScore:res.data.centerGroupScore,
          totalScore:res.data.totalScore,
        })
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  useEffect(()=>{
    getDetailData();
  },[])
  return (
    <PageContainer>
      <Descriptions column={6} items={[
        {
          label: "单据编号",
          children: detailData.code
        },
        {
          label: "部门名称",
          children: detailData.deptName
        },
        {
          label: "发起人",
          children: detailData.name
        },
        {
          label: "申请时间",
          children: detailData.time
        },
        {
          label: "自评总分",
          children: detailData.centerGroupScore
        },
        {
          label: "复核总分",
          children: detailData.totalScore
        }
      ]} />

      <Divider className={'my-[20px]'} />

      <Table
        className={"mb-[20px]"}
        scroll={{ x: 1600 }}
        dataSource={list}
        columns={columns}
        rowKey={(record) => `${record.id}`}
        bordered
      ></Table>

      {
        type === "detail" ? (
            <Row justify={'end'}>
              <Space>
                <Button onClick={() => {
                  Router.push('/performanceResultConfirmAndApply/performanceResultConfirm');
                }}>返回</Button>
              </Space>
            </Row>
          ) : (
          <Row justify={'end'}>
            <Space>
              <Button onClick={() => {
                Router.push('/performanceResultConfirmAndApply/performanceResultConfirm');
              }}>返回</Button>
              <Button type={'primary'} onClick={submit}>提交</Button>
            </Space>
          </Row>
        )
      }
    </PageContainer>
  )
}

export const getServerSideProps = getLayoutProps;
export default ComplaintCU;
